<template>
  <div class="vaw-avatar-container">
    <a-dropdown trigger="hover" size="large" position="bottom" @select="handleSelect">
      <div class="action-wrapper">
        {{ userDetails.userName }}
        <icon-caret-down class="tip" />
      </div>
      <template #content>
        <a-doption v-for="item of options" v-show="item.show" :key="item.key" :value="item.key">
          <template #icon>
            <component :is="item.icon" />
          </template>
          {{ item.label }}
        </a-doption>
      </template>
    </a-dropdown>
    <!-- 修改密码 -->
    <a-modal
      v-model:visible="passWordVisible"
      @before-close="passWordCFn"
      title="修改密码"
      width="600px"
      :mask-closable="false"
      title-align="start"
    >
      <a-form ref="passWordRef" :auto-label-width="true" :model="passWordForm">
        <a-form-item
          field="passWord"
          label="新密码"
          :rules="[{ required: true, message: '新密码不能为空' }]"
          :validate-trigger="['change', 'input']"
          asterisk-position="end"
        >
          <a-input v-model="passWordForm.passWord" placeholder="请输入新密码" allow-clear />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="passWordCFn">取消</a-button>
          <a-button type="primary" :loading="loadings" @click="passWordSub">确定</a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts">
  import useUserStore from '@/store/modules/user'
  import * as http from '@/api/http'
  import { loginOut, userLogout, adminpass, adminDetail, librartGetUrl } from '@/api/url'
  import { Modal, Message } from '@arco-design/web-vue'
  import { defineComponent, onMounted, ref, watch } from 'vue'
  import {
    IconUser as UserOutlined,
    IconPoweroff as LogoutOutlined,
    IconCaretDown as CaretDownOutlined,
    IconShareAlt as IconShareAlt,
    IconMessage as IconMessage,
  } from '@arco-design/web-vue/es/icon'
  import md5 from 'js-md5'
  import avtarStore from '@/store/modules/permission'
  import { useRouter } from 'vue-router'
  import { formpost, get } from '@/api/http'
  import { userDetail, userpass } from '@/api/user'
  export default defineComponent({
    name: 'VAWavatar',
    components: { UserOutlined, LogoutOutlined, CaretDownOutlined, IconShareAlt },
    setup() {
      const show = ref('78px')
      const userDetails: any = ref({})
      const userShow = ref(false)
      const passWordVisible = ref(false)
      const passWordForm = ref({
        passWord: '',
      })
      const loadings = ref(false)
      const userStore = useUserStore()
      const outStore = avtarStore()
      const options = [
        {
          label: '个人中心',
          key: 'personal-center',
          icon: 'UserOutlined',
          show: true,
        },

        {
          label: '修改密码',
          key: 'url',
          icon: 'IconShareAlt',
          show: true,
        },
        {
          label: '退出登录',
          key: 'logout',
          icon: 'LogoutOutlined',
          show: true,
        },
      ]

      const router = useRouter()
      const passWordRef = ref()
      // if (router.currentRoute.value.path.indexOf('children') == -1) {
      //   options.shift()
      // }
      function passWordFn() {
        passWordVisible.value = true
      }
      function passWordCFn() {
        passWordRef.value?.resetFields()
        passWordVisible.value = false
      }
      function passWordSub() {
        passWordRef.value?.validate().then((error: any) => {
          if (!error) {
            console.log('llllll')
            loadings.value = true

            if (window.location.pathname.split('/')[1] != 'children') {
              console.log(passWordForm.value.passWord)
              formpost({
                url: adminpass,
                data: () => {
                  return {
                    passWord: md5(passWordForm.value.passWord),
                  }
                },
              })
                .then((res: any) => {
                  if (res.code == 0) {
                    Message.success('修改成功')
                    loadings.value = false
                    http
                      .get({
                        url: loginOut,
                        data: () => {
                          return {}
                        },
                      })
                      .then((res) => {
                        if (res.code == 0) {
                          userStore.logout().then(() => {
                            router.push('/login')
                            Message.success(res.msg)
                            outStore.setNullMEnu([])
                          })
                        } else {
                          Message.error(res.msg)
                        }
                      })
                      .catch(console.log)
                  }
                })
                .catch(() => {
                  loadings.value = false
                })
            } else {
              formpost({
                url: userpass,
                data: () => {
                  return {
                    passWord: md5(passWordForm.value.passWord),
                  }
                },
              })
                .then((res: any) => {
                  if (res.code == 0) {
                    Message.success('修改成功')
                    loadings.value = false
                    http
                      .get({
                        url: userLogout,
                        data: () => {
                          return {}
                        },
                      })
                      .then((res) => {
                        if (res.code == 0) {
                          router.push('/children/login')
                          Message.success(res.msg)
                          outStore.setNullMEnu([])
                        } else {
                          Message.error(res.msg)
                        }
                      })
                      .catch(console.log)
                  }
                })
                .catch(() => {
                  loadings.value = false
                })
            }
          }
        })
      }
      function personalCenter() {
        router.push('/children/user/personalCenter')
      }
      const userDetailFn = () => {
        get({
          url: userDetail,
          data: {},
        }).then((res) => {
          if (res.code == 0) {
            userDetails.value = res.data
          }
        })
      }

      const adminDetailFn = () => {
        get({
          url: adminDetail,
          data: {},
        }).then((res) => {
          if (res.code == 0) {
            userDetails.value = res.data
          }
        })
      }

      function logout() {
        Modal.warning({
          title: '提示',
          content: '是否要退出当前账号？',
          titleAlign: 'start',
          okText: '退出',
          hideCancel: false,
          cancelText: '再想想',
          onOk: () => {
            if (window.location.pathname.split('/')[1] == 'children') {
              http
                .get({
                  url: userLogout,
                  data: () => {
                    return {}
                  },
                })
                .then((res) => {
                  if (res.code == 0) {
                    userStore.logout().then(() => {
                      router.push('/children/login')
                      Message.success(res.msg)
                      outStore.setNullMEnu([])
                    })
                  } else {
                    Message.error(res.msg)
                  }
                })
                .catch(console.log)
            } else {
              http
                .get({
                  url: loginOut,
                  data: () => {
                    return {}
                  },
                })
                .then((res) => {
                  if (res.code == 0) {
                    userStore.logout().then(() => {
                      router.push('/login')
                      Message.success(res.msg)
                      outStore.setNullMEnu([])
                    })
                  } else {
                    Message.error(res.msg)
                  }
                })
                .catch(console.log)
            }
          },
        })
      }

      function handleSelect(key: string) {
        console.log(key)
        switch (key) {
          case 'personal-center':
            personalCenter()
            break
          case 'url':
            passWordFn()
            break
          case 'logout':
            logout()
            break
        }
      }
      const showse = ref(false)
      const source = ref()
      const dataList: any = ref([])
      function close() {
        dataList.value = []
        source.value.close()
        showse.value = false
        console.log(111)
      }
      const top = ref(0)
      const scrollWrapperRef = ref() //滚动区域的父元素
      const handleScroll = () => {
        //滚动触发的事件
        const scrollWrapper = scrollWrapperRef.value // 获取滚动容器
        const { scrollTop, clientHeight, scrollHeight } = scrollWrapper // 获取滚动数据
        // console.log('scrollWrapper', scrollTop, clientHeight, scrollHeight)
        // 判断是否滚动到底部
        if (scrollTop == 0) {
          top.value = scrollTop
        } else if (scrollTop + clientHeight >= scrollHeight - 10) {
          top.value = -1
        }
      }

      function logFn() {
        showse.value = true
        if (window.EventSource) {
          // if (showsa.value == true) {
          // } else {
          // 建立连接
          source.value = new EventSource('/app/log/get')
          /**
           * 连接一旦建立，就会触发open事件
           */

          source.value.onopen = function (e: any) {
            console.log('建立连接', e)
          }
          /**
           * 客户端收到服务器发来的数据
           */
          source.value.onmessage = function (e: any) {
            console.log(e)
            if (dataList.value.length < 1000) {
              dataList.value.unshift(e.data)
            } else {
              dataList.value.unshift(e.data)
              dataList.value.pop()
            }
          }
          /**
           * 如果发生通信错误（比如连接中断），就会触发error事件
           */
          source.value.onerror = function (e: any) {
            // showsa.value = false
            if (e.readyState === EventSource.CLOSED) {
              console.log('连接关闭')
            } else {
              Message.error('超时请重试')
              // renewForm.value = {}
              showse.value = false
              source.value.close()
            }
          }
          // }
        } else {
          console.log('浏览器不支持SSE')
        }
      }
      const getLibrartGetUrl = () => {
        http
          .get({
            url: librartGetUrl,
            data: {},
          })
          .then((res) => {
            console.log(1111111111111, res)
            if (res.code == 0) {
              sessionStorage.setItem('imageUrl', res.data.url)
            }
          })
      }
      onMounted(async () => {
        getLibrartGetUrl()
        if (window.location.pathname.split('/')[1] == 'children') {
          userDetailFn()
        } else {
          adminDetailFn()
        }
      })
      // 监听当前路由
      watch(
        () => router.currentRoute.value,
        (newValue: any) => {
          if (newValue.name !== '金额缴纳') {
            if (window.location.pathname.split('/')[1] !== 'children') {
              options[0].show = false
              // newsFn()
            }
          }
        },
        { immediate: true }
      )
      return {
        userStore,
        options,
        handleSelect,
        show,
        userDetailFn,
        userShow,
        userDetails,
        passWordVisible,
        passWordForm,
        loadings,
        passWordFn,
        passWordRef,
        passWordSub,
        passWordCFn,
        close,
        logFn,
        showse,
        handleScroll,
        top,
        dataList,
      }
    },
  })
</script>

<style lang="less" scoped>
  .yin {
    box-shadow: 0px 10px 10px -8px #0000001a inset;
  }
  .yin1 {
    box-shadow: 0px -10px 10px -8px #0000001a inset;
  }
  .main-container {
  }
  .texts {
    width: 78px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .text1 {
    width: 50px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .texts1 {
    width: 50px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .title {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .vaw-avatar-container {
    .action-wrapper {
      display: flex;
      align-items: center;

      .avatar {
        display: flex;
        align-items: center;
        & > img {
          border: 1px solid #f6f6f6;
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 50%;
        }
      }
      .nick-name {
        margin: 0 5px;
        .tip {
          transform: rotate(0);
          transition: transform @transitionTime;
          margin-left: 2px;
        }
      }
    }
  }
  .vaw-avatar-container:hover {
    cursor: pointer;
    color: var(--primary-color);
    .tip {
      transform: rotate(180deg);
      transition: transform @transitionTime;
    }
  }
</style>
